package com.vcvt.verify.utils;

import com.vcvt.verify.model.Tree;
import com.vcvt.verify.model.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Description: 与树形结构有关的方法
 *
 * @author by xionghaohua
 * @date 2020/9/9
 */
public class TreeUtils {


    /**
     * 数组转成树 方法一
     * @param list 数组
     * @return 树
     */
    public static List<TreeNode> listToTree(List<TreeNode> list) {
        List<TreeNode> treeList  = new ArrayList<>();
        for (TreeNode node : list) {
            if (node.getPid() == 0) {
                treeList.add(findChildren(node, list));
            }
        }
        return treeList ;
    }

    private static TreeNode findChildren(TreeNode tree, List<TreeNode> list) {
        for (TreeNode node : list) {
            if (node.getPid().equals(tree.getId())) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<>());
                }
                tree.getChildren().add(findChildren(node, list));
            }
        }
        return tree;
    }


    /**
     * 数组转成树 方法二
     * @param list 数组
     * @return 树
     */
    public static List<TreeNode> listToTree2(List<TreeNode> list) {
        List<TreeNode> treeList = new ArrayList<TreeNode>();
        for (TreeNode tree : list) {
            if(tree.getPid() == 0){
                treeList.add(tree);
            }
        }
        for (TreeNode tree : list) {
            toTreeChildren(treeList,tree);
        }
        return treeList;
    }

    private static void toTreeChildren(List<TreeNode> treeList, TreeNode tree) {
        for (TreeNode node : treeList) {
            if(tree.getPid().equals(node.getId())){
                if(node.getChildren() == null){
                    node.setChildren(new ArrayList<>());
                }
                node.getChildren().add(tree);
            }
            if(node.getChildren() != null){
                toTreeChildren(node.getChildren(),tree);
            }
        }
    }


    /**
     * 使用递归方法建树
     */
    public static <T> List<Tree<T>> buildByRecursive(List<Tree<T>> modules, String parentId) {
        List<Tree<T>> trees = new ArrayList<>();
        for (Tree<T> treeNode : modules) {
            if (Objects.equals(treeNode.getParentId(), parentId)) {
                trees.add(findChildren(treeNode, modules));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     */
    private static <T> Tree<T> findChildren(Tree<T> treeNode, List<Tree<T>> nodes) {
        for (Tree<T> it : nodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, nodes));
            }
        }
        return treeNode;
    }

}
